package com.example.spb6;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.gson.Gson;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class MedicineActivity extends AppCompatActivity {

    private ListView medicineListView;
    private ArrayAdapter<Medicine> adapter;
    private List<Medicine> medicineList;
    // 在类顶部添加同步标记
    private boolean dataChanged = false;
    // 数据库配置
    static final String DB_URL = "jdbc:mysql://47.113.205.150:3306/test_user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    static final String DB_USER = "test_user";
    static final String DB_PASSWORD = "rYEraaXZfmWTGad3";

    private static final int SYNC_INTERVAL = 10000; // 10秒同步一次
    private Handler syncHandler;
    private Runnable syncRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medicine);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initializeViews();
        loadMedicines();
    }
    @Override
    protected void onResume() {
        super.onResume();

        // 设置自动同步数据的定时器
        syncHandler = new Handler();
        syncRunnable = new Runnable() {
            @Override
            public void run() {
                if (dataChanged) {
                    sendMedicineDataToMain();
                    dataChanged = false;
                }
                syncHandler.postDelayed(this, SYNC_INTERVAL);
            }
        };
        syncHandler.post(syncRunnable);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (syncHandler != null) {
            syncHandler.removeCallbacks(syncRunnable);
        }

    }
    private void initializeViews() {
        medicineListView = findViewById(R.id.medicine_list_view);
        medicineList = new ArrayList<>();
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, medicineList);
        medicineListView.setAdapter(adapter);

        medicineListView.setOnItemClickListener((parent, view, position, id) ->
                showMedicineDetails(medicineList.get(position)));

        Button sendButton = findViewById(R.id.btn_send_to_main);
        sendButton.setOnClickListener(v -> sendMedicineDataToMain());
    }

    private void loadMedicines() {
        new LoadMedicinesTask().execute();
    }

    @Override
    public void onBackPressed() {
        // 直接返回主界面，不再检查 dataChanged
        sendMedicineDataToMain(); // 确保数据同步
        super.onBackPressed(); // 正常关闭当前 Activity
    }

    // 修改sendMedicineDataToMain方法
    private void sendMedicineDataToMain() {
        try {
            Intent intent = new Intent();

            // 构建药物信息字符串
            StringBuilder medicineInfo = new StringBuilder();
            for (Medicine medicine : medicineList) {
                medicineInfo.append("药名: ").append(medicine.getName())
                        .append(", 过期时间: ").append(medicine.getExpirationDate())
                        .append(", 吃药时间: ").append(String.join(", ", medicine.getIntakeTimes()))
                        .append(", 用量: ").append(medicine.getDosage()).append("; ");
            }

            // 将信息添加到 Intent
            intent.putExtra("medicine_info", medicineInfo.toString());

            // 使用 Gson 序列化药物列表
            Gson gson = new Gson();
            String medicineListJson = gson.toJson(medicineList);
            intent.putExtra("medicine_list_json", medicineListJson);

            // 设置结果但不关闭 Activity
            setResult(RESULT_OK, intent);

            // 显示提示（可选）
            Toast.makeText(this, "数据已同步到主界面", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            Log.e("MedicineActivity", "发送药物数据失败: " + e.getMessage());
            Toast.makeText(this, "同步失败", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, R.id.add_medicine, Menu.NONE, "添加药物")
                .setIcon(android.R.drawable.ic_input_add)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        menu.add(Menu.NONE, R.id.delete_medicine, Menu.NONE, "删除药物")
                .setIcon(android.R.drawable.ic_delete)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        menu.add(Menu.NONE, R.id.edit_medicine, Menu.NONE, "修改药物") // 新增修改菜单
                .setIcon(android.R.drawable.ic_menu_edit)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.add_medicine) {
            showAddMedicineDialog();
            return true;
        } else if (item.getItemId() == R.id.delete_medicine) {
            showDeleteMedicineDialog();
            return true;
        } else if (item.getItemId() == R.id.edit_medicine) { // 新增修改处理
            showEditMedicineDialog();
            return true;
    }
        return super.onOptionsItemSelected(item);
    }
    // 显示修改对话框
    private void showEditMedicineDialog() {
        if (medicineList.isEmpty()) {
            Toast.makeText(this, "没有药物可修改", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("选择要修改的药物")
                .setItems(getMedicineNames(), (dialog, which) ->
                        showEditDetailsDialog(medicineList.get(which)))
                .show();
    }

    // 显示详细修改界面
    private void showEditDetailsDialog(Medicine medicine) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改药物信息");

        // 创建与添加药物相同的布局
        android.widget.LinearLayout layout = createMedicineInputLayout();

        // 设置药名
        ((android.widget.EditText) layout.getChildAt(0)).setText(medicine.getName());

        // 设置过期时间
        android.widget.TextView dateDisplay = (android.widget.TextView) layout.getChildAt(2);
        dateDisplay.setText(medicine.getExpirationDate());

        // 设置用量
        ((android.widget.EditText) layout.getChildAt(5)).setText(medicine.getDosage());
        // 设置库存
        //((android.widget.EditText) layout.getChildAt(6)).setText(String.valueOf(medicine.getStock()));

        // 添加现有的吃药时间
        android.widget.LinearLayout timeContainer = (android.widget.LinearLayout) ((android.widget.LinearLayout) layout.getChildAt(4)).getChildAt(0);
        for (String time : medicine.getIntakeTimes()) {
            // 为每个现有时间创建一个条目
            android.widget.LinearLayout timeEntryLayout = new android.widget.LinearLayout(this);
            timeEntryLayout.setOrientation(android.widget.LinearLayout.HORIZONTAL);

            // 时间文本
            android.widget.TextView timeText = new android.widget.TextView(this);
            timeText.setText(time);
            timeText.setTextSize(16);
            timeText.setPadding(10, 10, 10, 10);

            // 设置占比权重，让时间文本占据大部分空间
            android.widget.LinearLayout.LayoutParams textParams = new android.widget.LinearLayout.LayoutParams(
                    0, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
            timeText.setLayoutParams(textParams);

            // 删除按钮
            android.widget.Button deleteButton = new android.widget.Button(this);
            deleteButton.setText("删除");
            deleteButton.setOnClickListener(btn -> timeContainer.removeView(timeEntryLayout));

            // 添加到布局
            timeEntryLayout.addView(timeText);
            timeEntryLayout.addView(deleteButton);
            timeContainer.addView(timeEntryLayout);
        }

        builder.setView(layout);
        builder.setPositiveButton("保存", (dialog, which) -> {
            // 获取新的输入值
            String newName = ((android.widget.EditText) layout.getChildAt(0)).getText().toString().trim();
            String newExpiry = dateDisplay.getText().toString().trim();

            // 收集所有吃药时间
            List<String> newIntakeTimes = new ArrayList<>();
            for (int i = 0; i < timeContainer.getChildCount(); i++) {
                if (timeContainer.getChildAt(i) instanceof android.widget.LinearLayout) {
                    android.widget.LinearLayout timeEntry = (android.widget.LinearLayout) timeContainer.getChildAt(i);
                    android.widget.TextView timeText = (android.widget.TextView) timeEntry.getChildAt(0);
                    newIntakeTimes.add(timeText.getText().toString());
                }
            }
            String newTimesStr = String.join(",", newIntakeTimes);

            String newDose = ((android.widget.EditText) layout.getChildAt(5)).getText().toString().trim();
            //String stockStr = ((android.widget.EditText) layout.getChildAt(6)).getText().toString().trim();

            if (validateInput(newName, newExpiry, newTimesStr, newDose)) {
                Medicine newMed = new Medicine(newName, newExpiry, newIntakeTimes, newDose);
                new UpdateMedicineTask(medicine, newMed).execute();
            } else {
                Toast.makeText(MedicineActivity.this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    // 数据库更新任务
    private class UpdateMedicineTask extends DatabaseTask<Medicine> {
        private final Medicine oldMed;
        private final Medicine newMed;

        public UpdateMedicineTask(Medicine oldMed, Medicine newMed) {
            this.oldMed = oldMed;
            this.newMed = newMed;
        }

        @Override
        protected Boolean performDatabaseOperation(Connection conn, Medicine... params) throws Exception {
            // 更改SQL查询，确保正确匹配要更新的记录
            String updateQuery = "UPDATE medicines SET medicine_name=?, expiry_date=?, dosage=?, intake_times=? WHERE medicine_name=?";

            PreparedStatement stmt = conn.prepareStatement(updateQuery);

            // 设置新值
            stmt.setString(1, newMed.getName());
            stmt.setString(2, newMed.getExpirationDate());
            stmt.setString(3, newMed.getDosage());
            stmt.setString(4, String.join(",", newMed.getIntakeTimes()));
            //stmt.setInt( 5,newMed.getStock() );

            // 设置查询条件
            stmt.setString(5, oldMed.getName());

            // 执行更新并检查是否成功
            int rowsAffected = stmt.executeUpdate();

            // 记录更新结果
            Log.d("UpdateMedicineTask", "更新结果: 影响 " + rowsAffected + " 行");

            return rowsAffected > 0;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            if (success) {
                // 更新本地列表中的药物对象
                int index = medicineList.indexOf(oldMed);
                if (index != -1) {
                    medicineList.set(index, newMed);
                    adapter.notifyDataSetChanged();
                    dataChanged = true; // 标记数据已变更
                    Toast.makeText(MedicineActivity.this, "修改成功", Toast.LENGTH_SHORT).show();

                    // 立即同步到主界面，确保数据被保存
                    sendMedicineDataToMain();
                } else {
                    Toast.makeText(MedicineActivity.this, "药物不在列表中，请刷新", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(MedicineActivity.this, "修改失败，请重试", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void showMedicineDetails(Medicine medicine) {
        new AlertDialog.Builder(this)
                .setTitle("药物详情")
                .setMessage(getMedicineDetails(medicine))
                .setPositiveButton("确定", null)
                .show();
    }

    private String getMedicineDetails(Medicine medicine) {
        return "药名: " + medicine.getName() +
                "\n过期时间: " + medicine.getExpirationDate() +
                "\n吃药时间: " + String.join(", ", medicine.getIntakeTimes()) +
                "\n用量: " + medicine.getDosage();
    }


    private void showAddMedicineDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加药物");

        android.widget.LinearLayout layout = createMedicineInputLayout();
        builder.setView(layout);

        builder.setPositiveButton("确定", (dialog, which) -> handleAddMedicineInput(layout));
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private android.widget.LinearLayout createMedicineInputLayout() {
        android.widget.LinearLayout layout = new android.widget.LinearLayout(this);
        layout.setOrientation(android.widget.LinearLayout.VERTICAL);
        layout.setPadding(40, 20, 40, 20);

        // 药名输入框
        addEditTextToLayout(layout, "药名");

        // 过期时间使用日期选择器
        addDatePickerToLayout(layout, "过期时间");

        // 吃药时间使用时间选择器
        addTimePickersToLayout(layout, "吃药时间");

        // 用量输入框
        addEditTextToLayout(layout, "用量");

        //库存
       // addEditTextToLayout( layout, "库存" );

        return layout;
    }

    private void addEditTextToLayout(android.widget.LinearLayout layout, String hint) {
        android.widget.EditText editText = new android.widget.EditText(this);
        editText.setHint(hint);
        layout.addView(editText);
    }

    // 添加日期选择器
    private void addDatePickerToLayout(android.widget.LinearLayout layout, String labelText) {
        android.widget.TextView label = new android.widget.TextView(this);
        label.setText(labelText);
        layout.addView(label);

        android.widget.TextView dateDisplay = new android.widget.TextView(this);
        dateDisplay.setHint("点击选择日期");
        dateDisplay.setPadding(0, 10, 0, 10);
        dateDisplay.setTextSize(16);

        // 设置当前日期
        final Calendar calendar = Calendar.getInstance();
        final int year = calendar.get(Calendar.YEAR);
        final int month = calendar.get(Calendar.MONTH);
        final int day = calendar.get(Calendar.DAY_OF_MONTH);

        // 格式化并显示当前日期
        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        calendar.set(year, month, day);
        dateDisplay.setText(dateFormat.format(calendar.getTime()));

        // 点击时显示日期选择器
        dateDisplay.setOnClickListener(v -> {
            DatePickerDialog datePickerDialog = new DatePickerDialog(
                    this,
                    (view, selectedYear, selectedMonth, selectedDay) -> {
                        calendar.set(selectedYear, selectedMonth, selectedDay);
                        dateDisplay.setText(dateFormat.format(calendar.getTime()));
                    },
                    year, month, day);
            datePickerDialog.show();
        });

        layout.addView(dateDisplay);
    }

    // 添加时间选择器
    private void addTimePickersToLayout(android.widget.LinearLayout layout, String labelText) {
        android.widget.TextView label = new android.widget.TextView(this);
        label.setText(labelText);
        layout.addView(label);

        // 创建水平布局来存放已选择的时间和添加按钮
        android.widget.LinearLayout timeContainer = new android.widget.LinearLayout(this);
        timeContainer.setOrientation(android.widget.LinearLayout.VERTICAL);
        layout.addView(timeContainer);

        // 保存所有已选择时间的容器
        android.widget.LinearLayout selectedTimesContainer = new android.widget.LinearLayout(this);
        selectedTimesContainer.setOrientation(android.widget.LinearLayout.VERTICAL);
        timeContainer.addView(selectedTimesContainer);

        // 添加按钮 - 用于添加新的吃药时间
        android.widget.Button addTimeButton = new android.widget.Button(this);
        addTimeButton.setText("+ 添加吃药时间");
        addTimeButton.setOnClickListener(v -> {
            final Calendar calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);

            TimePickerDialog timePickerDialog = new TimePickerDialog(
                    this,
                    (view, selectedHour, selectedMinute) -> {
                        // 创建一个显示已选择时间的布局
                        android.widget.LinearLayout timeEntryLayout = new android.widget.LinearLayout(this);
                        timeEntryLayout.setOrientation(android.widget.LinearLayout.HORIZONTAL);

                        // 时间文本
                        String timeStr = String.format( Locale.getDefault(), "%02d:%02d", selectedHour, selectedMinute);
                        android.widget.TextView timeText = new android.widget.TextView(this);
                        timeText.setText(timeStr);
                        timeText.setTextSize(16);
                        timeText.setPadding(10, 10, 10, 10);

                        // 设置占比权重，让时间文本占据大部分空间
                        android.widget.LinearLayout.LayoutParams textParams = new android.widget.LinearLayout.LayoutParams(
                                0, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
                        timeText.setLayoutParams(textParams);

                        // 删除按钮
                        android.widget.Button deleteButton = new android.widget.Button(this);
                        deleteButton.setText("删除");
                        deleteButton.setOnClickListener(btn -> selectedTimesContainer.removeView(timeEntryLayout));

                        // 添加到布局
                        timeEntryLayout.addView(timeText);
                        timeEntryLayout.addView(deleteButton);
                        selectedTimesContainer.addView(timeEntryLayout);
                    },
                    hour, minute, true);
            timePickerDialog.show();
        });

        timeContainer.addView(addTimeButton);
    }


    private void handleAddMedicineInput(android.widget.LinearLayout layout) {
        // 获取药名
        String name = ((android.widget.EditText) layout.getChildAt(0)).getText().toString().trim();

        // 获取过期时间
        android.widget.TextView dateDisplay = (android.widget.TextView) layout.getChildAt(2);
        String expirationDate = dateDisplay.getText().toString();

        // 获取所有吃药时间
        android.widget.LinearLayout timeContainer = (android.widget.LinearLayout) ((android.widget.LinearLayout) layout.getChildAt(4)).getChildAt(0);
        List<String> intakeTimes = new ArrayList<>();

        for (int i = 0; i < timeContainer.getChildCount(); i++) {
            android.widget.LinearLayout timeEntry = (android.widget.LinearLayout) timeContainer.getChildAt(i);
            android.widget.TextView timeText = (android.widget.TextView) timeEntry.getChildAt(0);
            intakeTimes.add(timeText.getText().toString());
        }

        String intakeTimesStr = String.join(",", intakeTimes);

        // 获取用量
        String dosage = ((android.widget.EditText) layout.getChildAt(5)).getText().toString().trim();
        //获取库存
        //String stock =  ((android.widget.EditText) layout.getChildAt(6)).getText().toString().trim();
        if (validateInput(name, expirationDate, intakeTimesStr, dosage)) {
            Medicine medicine = new Medicine(name, expirationDate, intakeTimes, dosage);
            new AddMedicineTask().execute(medicine);
        } else {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
        }
       /* if (validateInput(name, expirationDate, intakeTimesStr, dosage, stock)) {
            int stock_int;
            stock_int = Integer.parseInt( stock );
            Medicine medicine = new Medicine(name, expirationDate, intakeTimes, dosage,stock_int);
            new AddMedicineTask().execute(medicine);
        } else {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
        }*/
    }

    private boolean validateInput(String... inputs) {
        for (String input : inputs) {
            if (input.isEmpty()) {
                return false;
            }
        }
        return true;
    }

    private void showDeleteMedicineDialog() {
        if (medicineList.isEmpty()) {
            Toast.makeText(this, "没有药物可删除", Toast.LENGTH_SHORT).show();
            return;
        }

        boolean[] checkedItems = new boolean[medicineList.size()];
        String[] medicineNames = getMedicineNames();
        // 创建一个 AlertDialog.Builder 对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("删除药物");
                //.setMultiChoiceItems(medicineNames, checkedItems, null)
        builder.setPositiveButton("删除", (dialog, which) -> deleteSelectedMedicines(checkedItems));
        builder.setNegativeButton("取消", null);
        // 设置多选列表
        builder.setMultiChoiceItems(medicineNames, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                // 处理用户的选择操作
                checkedItems[which] = isChecked;
                Log.e("_Mysql:",String.valueOf(checkedItems[which]));
            }
        });
        builder.show();
    }

    private String[] getMedicineNames() {
        String[] names = new String[medicineList.size()];
        for (int i = 0; i < medicineList.size(); i++) {
            names[i] = medicineList.get(i).getName();
        }
        return names;
    }

    private void deleteSelectedMedicines(boolean[] checkedItems) {
        List<Medicine> toRemove = new ArrayList<>();
        // 收集所有被选中的药物
        for (int i = 0; i < checkedItems.length; i++) {
            if (checkedItems[i]) {
                toRemove.add(medicineList.get(i));
            }
        }

        // 确保有药物被选中
        if (toRemove.isEmpty()) {
            Toast.makeText(this, "请选择要删除的药物", Toast.LENGTH_SHORT).show();
            return;
        }

        // 执行删除操作
        new DeleteMedicineTask().execute(toRemove.toArray(new Medicine[0]));
    }

    // 数据库任务基类
    private abstract class DatabaseTask<T> extends AsyncTask<T, Void, Boolean> {
        protected String errorMessage = "";
        protected Connection connection;

        @Override
        protected Boolean doInBackground(T... params) {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
                return performDatabaseOperation(connection, params);
            } catch (Exception e) {
                errorMessage = e.getMessage();
                return false;
            } finally {
                closeConnection(connection);
            }
        }

        protected abstract Boolean performDatabaseOperation(Connection connection, T... params) throws Exception;

        @Override
        protected void onPostExecute(Boolean success) {
            if (!success) {
                Toast.makeText(MedicineActivity.this, "操作失败: " + errorMessage, Toast.LENGTH_LONG).show();
            }
        }

        private void closeConnection(Connection connection) {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 加载药品数据任务
    private class LoadMedicinesTask extends DatabaseTask<Void> {
        @Override
        protected Boolean performDatabaseOperation(Connection connection, Void... voids) throws Exception {
            Statement stmt = connection.createStatement();
            stmt.executeUpdate("CREATE TABLE IF NOT EXISTS medicines (" +
                    "id INT AUTO_INCREMENT PRIMARY KEY, " +
                    "medicine_name VARCHAR(100) NOT NULL, " +
                    "expiry_date VARCHAR(20) NOT NULL, " +
                    "dosage VARCHAR(50) NOT NULL, " +
                    "description TEXT, " +
                    "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " +
                    "intake_times TEXT NOT NULL)");

            ResultSet rs = stmt.executeQuery("SELECT * FROM medicines");
            medicineList.clear();
            while (rs.next()) {
                medicineList.add(new Medicine(
                        rs.getString("medicine_name"),
                        rs.getString("expiry_date"),
                        Arrays.asList(rs.getString("intake_times").split(",")),
                        rs.getString("dosage")
                ));
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            super.onPostExecute(success);
            if (success) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    // 添加药品任务
    private class AddMedicineTask extends DatabaseTask<Medicine> {
        @Override
        protected Boolean performDatabaseOperation(Connection connection, Medicine... medicines) throws Exception {
            Medicine medicine = medicines[0];
            PreparedStatement pstmt = connection.prepareStatement(
                    "INSERT INTO medicines (medicine_name, expiry_date, dosage, intake_times) VALUES (?, ?, ?, ?)");
            pstmt.setString(1, medicine.getName());
            pstmt.setString(2, medicine.getExpirationDate());
            pstmt.setString(3, medicine.getDosage());
            pstmt.setString(4, String.join(",", medicine.getIntakeTimes()));

            pstmt.executeUpdate();

            medicineList.add(medicine);
            return true;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            super.onPostExecute(success);
            if (success) {
                adapter.notifyDataSetChanged();
                dataChanged = true; // 标记数据已变更
                Toast.makeText(MedicineActivity.this, "药物添加成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 删除药品任务
    private class DeleteMedicineTask extends DatabaseTask<Medicine> {
        @Override
        protected Boolean performDatabaseOperation(Connection connection, Medicine... medicines) throws Exception {
            // 创建一次性语句对象
            Statement stmt = connection.createStatement();

            for (Medicine medicine : medicines) {
                // 对每个药物执行删除操作
                String query = "DELETE FROM medicines WHERE medicine_name = '" +
                        medicine.getName() + "' AND expiry_date = '" +
                        medicine.getExpirationDate() + "'";
                stmt.executeUpdate(query);
                medicineList.remove(medicine);
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            super.onPostExecute(success);
            if (success) {
                adapter.notifyDataSetChanged();
                dataChanged = true; // 标记数据已变更
                Toast.makeText(MedicineActivity.this, "药物删除成功", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

